package org.scboy.coobi.utils;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.security.CodeSource;
import java.security.ProtectionDomain;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

public class JarPathUtil {

	static Log log=LogFactory.get();
	
	/**
	 * 获取启动根目录
	 */
	public static String getLocation() {
		ProtectionDomain protectionDomain = JarPathUtil.class.getProtectionDomain();
	    CodeSource codeSource = protectionDomain.getCodeSource();
	    URI location = null;
		try {
			location = (codeSource != null) ? codeSource.getLocation().toURI() : null;
		} catch (URISyntaxException e) {
			log.warn("无法读取到路径。");
		}
		//转码路径
	    String path = (location != null) ? location.getSchemeSpecificPart() : null;
	    if (path == null) {
		    throw new IllegalStateException("Unable to determine code source archive");
	    }
	    // 返回我们要执行的jar文件的绝对路径(java -jar xxx.jar中 xxx.jar的绝对路径)
	    File root = new File(path);
	    if (!root.exists()) {
		    throw new IllegalStateException("Unable to determine code source archive from " + root);
	    }
	    if(root.isDirectory()) {
	    	URL url=Thread.currentThread().getContextClassLoader().getResource("");
	    	File _root = new File(url.getFile());
	    	try {
				return URLDecoder.decode(_root.getParent(),"UTF-8");
			} catch (UnsupportedEncodingException e) {
				throw new RuntimeException(e);
			}
	    }else {
	    	try {
				return URLDecoder.decode(root.getParent(),"UTF-8");
			} catch (UnsupportedEncodingException e) {
				throw new RuntimeException(e);
			}
	    }
	}
}
